package cn.jlearn.proxy.agent.handler;

import cn.jlearn.proxy.agent.AgentStartApp;
import cn.jlearn.proxy.agent.container.ProxyClient;
import cn.jlearn.proxy.common.body.TcpBody;
import cn.jlearn.proxy.common.enums.MsgTypeEnum;
import cn.jlearn.proxy.common.packet.BsPacket;
import cn.jlearn.proxy.common.packet.TcpPacket;
import com.alibaba.fastjson.JSON;
import org.tio.client.intf.ClientAioHandler;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.TioConfig;
import org.tio.core.exception.TioDecodeException;
import org.tio.core.intf.Packet;

import java.nio.ByteBuffer;

/**
 * @author qianyingchao
 * @version 1.0
 * @date 2021/5/10 4:51 下午
 */
public class ForwardClientHandler implements ClientAioHandler {

    @Override
    public Packet heartbeatPacket(ChannelContext channelContext) {
        return null;
    }

    @Override
    public Packet decode(ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext) throws TioDecodeException {
        TcpPacket tcpPacket = new TcpPacket();
        byte[] dst = new byte[readableLength];
        buffer.get(dst);
        tcpPacket.setBody(dst);
        return tcpPacket;
    }

    @Override
    public ByteBuffer encode(Packet packet, TioConfig tioConfig, ChannelContext channelContext) {
        TcpPacket tcpPacket = (TcpPacket) packet;
        byte[] body = tcpPacket.getBody();
        ByteBuffer buffer = ByteBuffer.allocate(body.length);
        buffer.order(tioConfig.getByteOrder());
        buffer.put(body);
        return buffer;
    }

    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
        TcpPacket tcpPacket = (TcpPacket) packet;
        TcpBody tcpBody = new TcpBody(tcpPacket.getBody(), (String) channelContext.get("bsId"));
        BsPacket bsPacket = new BsPacket(MsgTypeEnum.TCP_FORWARD_RES.getCode(), JSON.toJSONBytes(tcpBody));

        Tio.sendToBsId(ProxyClient.clientTioConfig, AgentStartApp.TOKEN, bsPacket);
    }

}
